package com.github.easyms.server.controller.common;

import com.github.easyms.common.entity.auth.User;
import com.github.easyms.common.property.EasymsProperties;
import com.github.easyms.common.util.RequestHelper;
import com.github.easyms.common.util.ValidatorHelper;
import com.github.easyms.common.vo.ErrorVo;
import com.github.easyms.common.vo.auth.LoginCheckVo;
import com.github.easyms.common.vo.auth.LoginSuccessVo;
import com.github.easyms.server.service.auth.UserService;
import io.swagger.annotations.*;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Leo.Liao
 * 程序入口控制器
 * @date 2020-04-09 17:02:38
 */
@Controller
@Api(tags = {"系统入口"})
@RequestMapping("/index")
public class IndexController {

    @Resource
    private UserService userService;

    @Resource
    private EasymsProperties easymsProperties;

    @ApiOperation(value = "登陆校验")
    @ApiResponses({ @ApiResponse(code = 400,message = "登陆失败",response = ErrorVo.class) })
    @ApiImplicitParam(name = HttpHeaders.AUTHORIZATION)
    @ResponseBody
    @PostMapping("/loginCheck")
    public ResponseEntity<LoginSuccessVo> loginCheck(@RequestBody LoginCheckVo loginCheckVo, HttpServletResponse response){
        // 参数校验
        ValidatorHelper.validateEntity(loginCheckVo);
        // 用户名密码校验
        User user = userService.loginCheck(loginCheckVo);
        // 获取用户密码状态
        String pwdStatus = userService.checkPwdStatus(user.getUserId());
        // 生成Toke
        String strToken = userService.createToken(user.getUserId());
        // 保存TOKEN(header/cookie)
        response.setHeader(HttpHeaders.AUTHORIZATION, strToken);
        RequestHelper.setCookie(response,HttpHeaders.AUTHORIZATION,strToken,null);
        // 保存用户语言(header/cookie)
        response.setHeader(HttpHeaders.ACCEPT_LANGUAGE, user.getLanguage());
        RequestHelper.setCookie(response,HttpHeaders.ACCEPT_LANGUAGE,user.getLanguage(),null);
        // 响应数据
        LoginSuccessVo loginSuccessVo = new LoginSuccessVo();
        loginSuccessVo.setToken(strToken);
        loginSuccessVo.setPwdStatus(pwdStatus);
        return ResponseEntity.ok(loginSuccessVo);
    }

    @ApiOperation(value = "获取版本号")
    @ApiImplicitParam(name = HttpHeaders.AUTHORIZATION)
    @ResponseBody
    @GetMapping("/getVersion")
    public ResponseEntity<String> getVersion(){
        return ResponseEntity.ok(easymsProperties.getVersion());
    }

}
